package com.situ.saveqq;

import android.content.Context;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 把账号和密码保存到data.txt文件中
 */
public class FileSaveQQ {

    /**
     * 保存用户信息
     * @param context Android 的上下文环境
     * @param number  账号
     * @param password  密码
     * @return   true:保存成功， false：保存失败
      */
    public static boolean saveUserInfo(Context context, String number, String password) {
        // 在IDEA里面通过Alt+Enter
        FileOutputStream fileOutputStream = null;
        try {
            // fileOutputStream = new FileOutputStream();
            fileOutputStream = context.openFileOutput("data.txt", Context.MODE_PRIVATE);
            //  zhangsan:123
            String string = number + ":" + password;
            fileOutputStream.write(string.getBytes());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return  false;
        } catch (IOException e) {
            e.printStackTrace();
            return  false;
        } finally {
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return true;
    }

    public static Map<String, String> getUserInfo(Context context) {
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = context.openFileInput("data.txt");
            byte[] buffer = new byte[fileInputStream.available()];
            fileInputStream.read(buffer);

            // zhangsan:123
            String content = new String(buffer);
            String[] array = content.split(":"); // ["zhansgan", "123"]
            HashMap<String, String> map = new HashMap<>();
            map.put("number", array[0]);
            map.put("password", array[1]);
            return map;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return null;
    }


}
